package com.sskj.ffmpeg;

import com.sskj.websocket.R;
import lombok.Value;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController
@RequestMapping("/api/camera")
public class videoStreamController {

//    @Value("${mapFile.path}")  // 存储地址
    private String filePath = "E:\\hls";
//    @Value("${mapFile.address}") // 外层文件夹名
    private String address;
//    @Value("${mapFile.ip}")  // 映射ip
    private String ip;

    @GetMapping("/changePreviewUrl")
    public R changePreviewUrl(String rtspUrl, String codeName) {
        this.stopFFmpeg();
        return R.ok(this.GetCameraPreviewURL(rtspUrl, codeName));
    }

    @GetMapping("/stopPreviewUrl")
    public R stopPreviewUrl() {
        return R.ok(this.stopFFmpeg());
    }

    private Process ffmpegProcess;
    private String outputName = "";

    public String GetCameraPreviewURL(String url, String codeName) {
        // 工作目录
        String currentPath = System.getProperty("user.dir");
        // 获取当前类的路径
        // String classPath = GetClassPathExample.class.getResource("/").getPath();
        // 获取类路径中的资源文件路径
        // JAR 包中，它将返回 null
        // String resourcePath = GetResourcePathExample.class.getClassLoader().getResource("example.txt").getPath();

         this.getFilePath();

        String ffmpegPath = "E:\\LearningSpace\\ffmpeg-master-latest-win64-gpl\\bin\\ffmpeg.exe";

        // RTSP 输入 URL 和 HLS 输出设置
        String rtspUrl = "rtsp://admin:Langhong@2023@192.168.88.161:554/Streaming/Channels/101";

        //
        if (StringUtils.isNotBlank(codeName)) {
//            int nameIdx =  codeName.lastIndexOf("\\");
            outputName = codeName;
//            if (nameIdx != -1) {
//                outputName = codeName.substring(0, nameIdx);
//            }
        }
//        String outputPath = filePath.replaceAll("/", "\\\\") + outputName + ".m3u8";
        String outputPath = "E:\\hls\\" + outputName + ".m3u8";
        //outputPath = "D:\\apache-tomcat-8\\webapps\\output\\" + outputName + ".m3u8";

        // FFmpeg 命令
        String[] command = {
                ffmpegPath,
                "-i", rtspUrl,
                "-c:v", "libx264",
                "-preset", "fast",
                "-crf", "20",
                "-c:a", "aac",
                "-b:a", "128k",
                "-f", "hls",
                "-hls_time", "10",
                "-hls_list_size", "10",
                "-hls_flags", "delete_segments",
                outputPath
        };

//        String command = "%s -i %s -c:v libx264 -preset fast -crf 20 -c:a aac -b:a 128k -f hls -hls_time 10 -hls_list_size 10 -hls_flags delete_segments %s";
//        command = String.format(command, ffmpegPath, rtspUrl, outputPath);

        String result = "";
        try {
            // 创建 ProcessBuilder 实例
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);

            // 启动进程
            ffmpegProcess = processBuilder.start();

            /*
            // 读取并打印 FFmpeg 的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;

            //reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            System.out.println(reader.readLine());

            while ((line = reader.readLine()) != null) {
                if (result == "") {
                    result = "/output/"+outputName+".m3u8";
                    System.out.println(line);
                }
            }
             */

            result = outputName+".m3u8";

            //new Thread(() -> {
                String line = "";
                File dir = new File(outputPath);
                int j = 0;
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(ffmpegProcess.getInputStream()))) {
					// 生成文件后返回视频路径
                    while (line != null || dir.exists()) {
                        line = reader.readLine();
                        dir = new File(outputPath);
                        System.out.println("line " + Integer.toString(j) + line);
                        System.out.println("dire " + Integer.toString(j) + " " + dir.exists());
                        if (line == null || dir.exists()) {
                            break;
                        }
                        j++;
                    }

                    if (line != null) {
                        return  result;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            //}).start();

            // 等待进程结束
            int exitCode = ffmpegProcess.waitFor();
            result = Integer.toString(exitCode);
            System.out.println("FFmpeg exited with code " + exitCode);
            ffmpegProcess = null;
            outputName = "";
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String stopFFmpeg() {
    	// 单进程
        String result = "false";
        if (ffmpegProcess != null) {
            ffmpegProcess.destroy(); // 终止FFmpeg进程
            System.out.println("FFmpeg process stopped.");
            ffmpegProcess = null;
            result = "true";
        }
        if (outputName != "") {
            this.delFileInPath();
            outputName = "";
        }
        return result;
    }


    /**
     * 判断创建文件
     * */
    public void getFilePath() {
        // 创建目录
        File dir = new File(filePath);
        boolean start = dir.exists();
        if (!dir.exists()) {
            dir.mkdirs();
            start = dir.exists();
        }
        System.out.println(start);
    }
    /**
     * 删除文件夹下的文件
     * */
    public void delFileInPath() {
        File directory = new File(filePath);

        // 检查目录是否存在并且是一个目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录中的所有文件和子目录
            File[] files = directory.listFiles();

            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        if (outputName != "") {
                            if (file.getName().indexOf(outputName) != -1) {
                                file.delete();
                            }
                        } else {
                            System.out.println("文件: " + file.getName());
                        }
                    } else if (file.isDirectory()) {
                        System.out.println("目录: " + file.getName());
                    }
                }
            } else {
                System.out.println("无法列出目录中的文件");
            }
        } else {
            System.out.println("指定的路径不是一个有效的目录");
        }
    }
}

